import NProgress from 'nprogress'
import useRsaStore from "@/store/modules/RsaStore.js"
import {getRsaPublicKeyAPI} from "@/api/rsa.js";
import useAccountStore from "@/store/modules/AccountStore.js";
import {ERROR_ROUTE} from "@/router/routes/error/error.js";
import {LOGIN_ROUTE} from "@/router/routes/login/login.js";
import {loginEffectiveAPI} from "@/api/login.js";
import {HOME_ROUTE} from "@/router/routes/home/home.js";
import {CATEGORY_ROUTE} from "@/router/routes/category/category.js";
import {CATEGORY_PRODUCT_LIST_ROUTE} from "@/router/routes/category/CategoryProductList.js";
import {PRODUCT_ROUTE} from "@/router/routes/product/product.js";
import {MORE_ROUTE} from "@/router/routes/more/more.js";
import {ORDER_DETAIL_ROUTE} from "@/router/routes/order/OrderDetail.js";
import {SEARCH_ROUTE} from "@/router/routes/search/search.js";
import {SEARCH_LIST_ROUTE} from "@/router/routes/search/SearchList.js";
import {LIU_YAN_ROUTE} from "@/router/routes/liu/LiuYan.js";

// 无需获取 rsa 公钥即可访问的页面
const notNeedRsaRoutes = [ERROR_ROUTE]

// 商品页面加载动画元素
let dataLoadingDivElement = null
let orderLoadingDivElement = null

// ************************
// * 全局路由前置守卫处理函数 *
// ************************
export async function beforeEachHandler(to, from, next) {
    // 开启进度条
    NProgress.start()
    // 无需 rsa 公钥即可访问的页面
    if (notNeedRsaRoutes.includes(to.name)) {
        next()
        return
    }
    // RSA store
    const rsaStore = useRsaStore()
    // rsa 公钥
    const rsaPublicKey = rsaStore.publicKey
    // 没有获取 rsa 公钥，先进行获取
    if (rsaPublicKey === null || rsaPublicKey === undefined || rsaPublicKey.length <= 0) {
        const res = await getRsaPublicKeyAPI()
        // 发生错误
        if (!res) {
            next({name: ERROR_ROUTE})
            return
        }
    }
    // 执行路由全局前置守卫逻辑处理
    const res = await handleBeforeEach(to, from, next)
    if (res) {
        // 可以前往要前往的页面
        next()
    }
}

// ************************
// * 全局路由前置守卫处理函数 *
// ************************
export function afterEachHandler(to, from) {
    // 结束加载条
    NProgress.done()
    // 要前往的页面的路由 name
    const toRouteName = to.name
    // 前往商品页面
    if (toRouteName === PRODUCT_ROUTE) {
        // 移除加载动画
        document.body.removeChild(dataLoadingDivElement)
    }
    // 前往订单详情页面
    if (toRouteName === ORDER_DETAIL_ROUTE) {
        document.body.removeChild(dataLoadingDivElement)
    }
}

// *******************
// * 不需要进行登录路由 *
// *******************
const notNeedLoginRoutes = [
    ...notNeedRsaRoutes,
    LOGIN_ROUTE,
    HOME_ROUTE,
    CATEGORY_ROUTE,
    CATEGORY_PRODUCT_LIST_ROUTE,
    PRODUCT_ROUTE,
    MORE_ROUTE,
    SEARCH_ROUTE,
    SEARCH_LIST_ROUTE,
    LIU_YAN_ROUTE,
]

// ***************************
// * 执行前置守卫中执行的逻辑处理 *
// ***************************
async function handleBeforeEach(to, from, next) {
    // 要前往的页面的路由 name
    const toRouteName = to.name
    // 前往商品页面
    if (toRouteName === PRODUCT_ROUTE) {
        // 添加加载动画
        dataLoading('商品正在快速赶来...')
    }
    // 前往订单详情页面
    if (toRouteName === ORDER_DETAIL_ROUTE) {
        dataLoading('订单正在赶来的路上...')
    }
    // 访问的路由不需要登录
    if (notNeedLoginRoutes.includes(toRouteName)) {
        return true
    }
    const accountStore = useAccountStore()
    // account
    const account = accountStore.account
    // 未登录过
    if (account === null || account === undefined || account.length <= 0) {
        // 前往登录
        next({name: LOGIN_ROUTE, query: {toRouteName}})
        return false
    }
    // 登录过，校验登录是否还有效
    let res = await loginEffectiveAPI()
    // 登录无效，前往登录
    if (!res) {
        next({name: LOGIN_ROUTE, query: {toRouteName}})
        return false
    }
    return true
}

/**
 * 商品页面加载动画
 */
const dataLoading = (title) => {
    dataLoadingDivElement = document.createElement('div');
    dataLoadingDivElement.className = 'data-loading fixed top-0 lef-0 z-1 h-screen bg-white dark:bg-neutral-900'
    const titleDiv = document.createElement('div');
    titleDiv.className = 'title text-3xl pt-16 pb-4 flex-center dark:text-gray-100'
    // titleDiv.innerText = '商品正在快速赶来...'
    titleDiv.innerText = title
    dataLoadingDivElement.appendChild(titleDiv)
    const videoElement = document.createElement('video');
    videoElement.src = '/xwb/bookmall/user/images/ProductLoading.mp4'
    videoElement.autoplay = true
    videoElement.loop = true
    videoElement.muted = true
    dataLoadingDivElement.appendChild(videoElement)
    document.body.appendChild(dataLoadingDivElement)
}

const orderLoading = () => {
    orderLoadingDivElement = document.createElement('div');
    orderLoadingDivElement.className = 'fixed top-0 lef-0 z-10 w-screen h-screen bg-neutral-900 flex-center'
    const loaderBox = document.createElement('div');
    loaderBox.className = 'loader loader-2 z-10'
    const svgEle = document.createElement('svg')
    svgEle.className = 'loader-star z-10'
    svgEle.xmlns = 'http://www.w3.org/2000/svg'
    svgEle['xmlns:xlink'] = 'http://www.w3.org/1999/xlink'
    svgEle.version = '1.1'
    const polygonEle = document.createElement('polygon')
    polygonEle.points = '29.8 0.3 22.8 21.8 0 21.8 18.5 35.2 11.5 56.7 29.8 43.4 48.2 56.7 41.2 35.1 59.6 21.8 36.8 21.8'
    polygonEle.fill = '#18ffff'
    svgEle.appendChild(polygonEle)
    loaderBox.appendChild(svgEle)
    const loaderCircleBox = document.createElement('div');
    loaderCircleBox['className'] = 'loader-circles'
    orderLoadingDivElement.appendChild(loaderBox)
    document.body.appendChild(orderLoadingDivElement)
}